<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2021/08/25} {15:45} 
 */

namespace wanghua\general_utility_tools_php\framework;


use app\common\model\TabConf;
use think\Cache;
use think\Controller;
use think\Db;
use think\Exception;
use think\Request;
use wanghua\general_utility_tools_php\api\ApiDocument;
use wanghua\general_utility_tools_php\tool\MySqlTools;
use wanghua\general_utility_tools_php\tool\Tools;

/**
 * 基础架构
 *
 * Class BaseController
 * @package app\index\controller
 */
class BaseController extends Controller
{
    public function __construct()
    {
        parent::__construct();

        //校验系统维护状态 start
        $chm = $this->checkMaintain();
        if ($chm['is_maintain']) {
            if ($chm['users_ids']) {
                //解析openid
                if (!in_array(api_user_info('id'), explode(',', $chm['users_ids']))) {
                    //白名单之外维护中
                    //Tools::log_to_write_txt([
                    //    '维护测试'=>$chm['users_ids'],
                    //    'my'=>index_user_openid()
                    //]);
                    return $this->error($chm['msg']);
                }
            } else {
                //不存在，直接维护中
                return $this->error($chm['msg'] . '！');
            }
        }
        //校验系统维护状态 end
    }

    /**
     * desc：空控操作
     * author：wh
     */
    function _empty($info='')
    {

    }
    /**
     * desc：检查路径维护状态
     *
     * “===”完全匹配，不能使用like
     *
     * author：wh
     */
    protected function checkMaintain(){
        $configs = Db::table(TabConf::$fa_sys_maintain_config)
            ->where('status','1')
            ->cache()
            ->select();

        //模块
        $strmodule = request()->module();
        foreach ($configs as $config){
            if($strmodule == $config['url']){
                //模块维护中
                return ['is_maintain'=>true,'msg'=>$config['msg'],'users_ids'=>$config['users_ids']];
            }
        }

        //模块/控制器
        $strcontroller = strtolower(request()->module().'/'.request()->controller());
        foreach ($configs as $config){
            if($strcontroller == $config['url']){
                //模块维护中
                return ['is_maintain'=>true,'msg'=>$config['msg'],'users_ids'=>$config['users_ids']];
            }
        }

        //模块/控制器/方法
        $straction = strtolower(request()->module().'/'.request()->controller().'/'.request()->action());
        foreach ($configs as $config){
            if($straction == $config['url']){
                //模块维护中
                return ['is_maintain'=>true,'msg'=>$config['msg'],'users_ids'=>$config['users_ids']];
            }
        }

        //未维护
        return ['is_maintain'=>false,'msg'=>'服务运行中'];
    }
    /**
     * desc：清空系统缓存
     *
    /index/Test/clearCache
     *
     * author：wh
     */
    function clearCache(){

        Tools::clear_cache();
    }
    /**
     * eg：/index/test/buildTablesConf
     *
     * desc：构建统一的表名配置
     *
     * author：wh
     */
    function buildTablesConf(){

        (new MySqlTools())->buildTablesConf();

    }

    /**
     * desc：创建&更新接口文档
     *
     * 默认存放在/public/api_docs/api_list.md
     *
     * author：wh
     */
    function buildApiDoc()
    {
        $obj = new ApiDocument();
        //根据自己的实际情况设置直接继承类（仅供参考）
        $obj->extends_base_class = 'app\\api\\controller\\BaseHttpApi,wanghua\\general_utility_tools_php\\framework\\base\\BaseWechatAuthController';
        //设置过滤的类（仅供参考）
        $obj->setFilterClass([
            'BaseCommonController',
            'BaseHttpApi',
            'BaseWssApi',
            'Wsspush',
            'BaseController',
            'BaseAuthController',
            //'BaseWechatAuthController',
            'BasePublicController'
        ]);
        $obj->setFilterFunction([
            'buildApiDoc',
            'buildTablesConf',
            'checkfailed',
            'clearCache',
            'defaultAuth',
            'operateLog',
            'checkMaintain',
            '_empty'
        ]);
        //构建接口文档
        $obj->buildDoc();
        //生成html
        $html = $obj->buildApiDocHtml();
        $path = Tools::get_root_path().'/public/api_docs/';
        if(!file_exists($path)){
            mkdir($path,0777,true);
        }
        file_put_contents($path.'api_list.html',$html);
        echo "<a href='/api_docs/api_list.html' target='_blank'>api_list.html</a>";

    }

    /**
     * desc：用户操作日志
     * author：wh
     */
    protected function operateLog($msg,$users_id=0,$username='',$name=''){
        $tbname = 'fa_users_operate_log';
        $sql = "
        CREATE TABLE IF NOT EXISTS `{$tbname}` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `users_id` int(10) unsigned DEFAULT '0' COMMENT '用户ID',
  `username` varchar(15) DEFAULT '' COMMENT '用户名',
  `name` varchar(20) DEFAULT '' COMMENT '名称',
  `url` varchar(60) DEFAULT '' COMMENT 'URL',
  `msg` varchar(90) DEFAULT '' COMMENT '做了什么',
  `ip` varchar(30) DEFAULT '' COMMENT '登录ip',
  `input` text COMMENT '提交参数',
  `create_time` timestamp NULL DEFAULT NULL COMMENT '登陆时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=54 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='用户操作日志';";

        if(cache('cache_db_tables_now_project')){
            $table_arr = cache('cache_db_tables_now_project');
        }else{
            $table_arr = Tools::get_tables();
        }
        //表是否存在
        if(!in_array($tbname,$table_arr)){
            cache('cache_db_tables_now_project',$table_arr);
            Db::execute($sql);
        }

        $data = [
            'users_id'=>$users_id,
            'username'=>$username,
            'name'=>$name,
            'url'=>request()->url(),
            'msg'=>$msg,
            'ip'=>request()->ip(),
            'input'=>json_encode(input(),JSON_UNESCAPED_UNICODE),
        ];
        Db::table($tbname)->data($data)->insert();

    }
}